from datetime import datetime

from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import as_serializer_error

from user.models import ProjUserGroup
from .models import Question, Choice, Blank, QuestionGroup, UserExerciseLog

from django.core.exceptions import ValidationError as DjangoValidationError


class QuestionSerializer(serializers.ModelSerializer):
    title = serializers.SerializerMethodField()
    type = serializers.CharField()
    label = serializers.CharField()

    # type = serializers.CharField(source='get_type_display')

    class Meta:
        model = Question
        fields = ('id', 'title', 'label', 'type')

    def get_title(self, obj):
        if obj.name:
            return obj.name
        return obj.stem[:5]


class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'


class BlankSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blank
        fields = '__all__'


class QuestionDetailSerializer(serializers.ModelSerializer):
    choice = ChoiceSerializer(required=False, allow_null=True)
    blank = BlankSerializer(required=False, allow_null=True)
    type = serializers.CharField()

    class Meta:
        model = Question
        fields = '__all__'

    # def validate(self, data):
    #     """blank_data = data.get('blank')
    #     choice_data = data.get('choice')
    #
    #     if blank_data and choice_data:
    #         raise serializers.ValidationError("类型冲突：同时提供了选择和填空信息")
    #
    #     if choice_data:
    #         choice_serializer = ChoiceSerializer(data=choice_data)
    #         choice_serializer.is_valid(raise_exception=True)
    #
    #     return data"""
    #     if ('blank' in data) and ('choice' in data):
    #         raise ValidationError("类型冲突")
    #     elif ('blank' not in data) and ('choice' not in data):
    #         raise ValidationError("类型缺失")
    #     return data

    def create(self, validated_data):
        validated_data['create_time'] = datetime.now()  # 使用当前时间
        validated_data['update_time'] = validated_data['create_time']
        choice_data = validated_data.pop('choice', None)
        blank_data = validated_data.pop('blank', None)
        question = Question.objects.create(**validated_data)
        if choice_data:
            choice_s = ChoiceSerializer(data=choice_data)
            if choice_s.is_valid():
                choice_s.validated_data['question'] = question
                choice_instance = choice_s.save()
                validated_data['choice'] = choice_instance
        elif blank_data:
            blank_s = BlankSerializer(data=blank_data)
            if blank_s.is_valid():
                blank_s.validated_data['question'] = question
                blank_instance = blank_s.save()
                validated_data['blank'] = blank_instance

        return question

    def update(self, instance, validated_data):
        choice_data = validated_data.pop('choice', None)
        blank_data = validated_data.pop('blank', None)
        if choice_data is not None:
            # 更新关联的 choice（假设它已经存在）
            choice_instance = instance.choice
            ChoiceSerializer(partial=True).update(instance=choice_instance, validated_data=choice_data)
        elif blank_data is not None:
            blank_instance = instance.blank
            BlankSerializer(partial=True).update(instance=blank_instance, validated_data=blank_data)

        super().update(instance=instance, validated_data=validated_data)
        instance.update_time = datetime.now()
        instance.save()
        return instance


class QuestionGroupSerializer(serializers.ModelSerializer):
    creator_name = serializers.CharField(source='creator.username', read_only=True)

    class Meta:
        model = QuestionGroup
        fields = ['id', 'name', 'creator_name', 'create_time']


class QuestionGroupDetailSerializer(serializers.ModelSerializer):
    questions = QuestionSerializer(many=True, read_only=True, required=False)
    def create(self, validated_data):
        user_groups_data = validated_data.pop('user_groups')

        validated_data['create_time'] = datetime.now()
        question_group = QuestionGroup.objects.create(**validated_data)

        question_group.user_groups.set(user_groups_data)

        return question_group

    class Meta:
        model = QuestionGroup
        fields = '__all__'


class LogSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserExerciseLog
        fields = '__all__'
